interface ValidationRegs {
  email: RegExp;
  password: RegExp;
  username: RegExp;
  idCard: RegExp;
}
const regs: ValidationRegs = {
  email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
  password:
    /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
  username: /^[a-zA-Z0-9_]{4,16}$/,
  idCard:
    /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/, // 18位身份证号正则表达式
};

// 校验函数
const verify = (
  rule: any,
  value: string,
  reg: RegExp,
  callback: (error?: Error) => void
) => {
  if (value) {
    if (reg.test(value)) {
      callback(); //通过
    } else {
      callback(new Error(rule.message || "格式不正确"));
    }
  } else {
    callback();
  }
};

//表单规则校验
const email = (rule: any, value: string, callback: (error?: Error) => void) => {
  verify(rule, value, regs.email, callback);
};
const password = (
  rule: any,
  value: string,
  callback: (error?: Error) => void
) => {
  verify(rule, value, regs.password, callback);
};
const username = (
  rule: any,
  value: string,
  callback: (error?: Error) => void
) => {
  verify(rule, value, regs.username, callback);
};
const idCard = (
  rule: any,
  value: string,
  callback: (error?: Error) => void
) => {
  verify(rule, value, regs.idCard, callback);
};

export default {
  email,
  password,
  username,
  idCard,
  regs,
};
